package com.jiezuo.common.util;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
public class SortUtil {


	/**
	 * 拖拽排序
	 * 
	 * @param list       排序的list

	 * @param orderField 排序的字段（对象的排序属性）
	 * @throws Exception
	 */
	public static List sort(List list, String orderField)  {


		try {
			List sorts = new ArrayList();
			for (Object o : list) {
				Field dataField = o.getClass().getDeclaredField(orderField);
				dataField.setAccessible(true);
				Object object = dataField.get(o);
				sorts.add(Integer.valueOf(object.toString()));
			}
			/**
			 *
			Object object = list.get(oldOrder - 1);
			list.remove(oldOrder - 1);
			list.add(newOrder - 1, object);
			for (Object oo : list) {
				System.out.println(oo);
			}*/
			Collections.sort(sorts);
			for (int i = 0; i < list.size(); i++) {
				Object o = list.get(i);
				Field dataField = o.getClass().getDeclaredField(orderField);
				dataField.setAccessible(true);
				dataField.set(o,String.valueOf(sorts.get(i)));
			}
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return list;
	}

}
